//
//  Keychain.m
//  owa-notifier
//
//  Created by Sandeep Mistry on 13/07/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "Keychain.h"

const NSString* serviceName = @"OWA Notifier";

@implementation Keychain

-(NSString*) username
{
	SecKeychainAttribute attributes[8];
	SecKeychainAttribute attr;
	
	SecKeychainAttributeList list;
	
	SecKeychainItemRef itemRef;
	
	attributes[0].tag = kSecAccountItemAttr;
	
	list.count = 1;
	list.attr = attributes;
	
	attr = list.attr[0];
	
	if(SecKeychainFindGenericPassword(NULL, [serviceName length], [serviceName UTF8String], 0, NULL, NULL, NULL, &itemRef))
	{
		return nil;
	}
	
	// use this version if you don't really want the password,
	// but just want to peek at the attributes
	if(SecKeychainItemCopyContent(itemRef, NULL, &list, NULL, NULL))
	{
		return nil;
	}

	NSString* username = [[[NSString alloc] initWithBytes:attributes[0].data length:attributes[0].length encoding:NSUTF8StringEncoding] autorelease];
		
	SecKeychainItemFreeContent(&list, NULL);
	
	return username;
}

-(NSString*) password
{
	UInt32 passwordLength;
	void* passwordData;
	
	NSString* password = nil;
	
	if(!SecKeychainFindGenericPassword(NULL, [serviceName length], [serviceName UTF8String], 0, NULL, &passwordLength, &passwordData, NULL))
	{
		password = [[[NSString alloc] initWithBytes:passwordData length:passwordLength encoding:NSUTF8StringEncoding] autorelease];
		SecKeychainItemFreeContent(NULL, passwordData);
	}
	
	return password;
}

-(void) setUsername:(NSString*)newUsername withPassword:(NSString*)newPassword
{
	SecKeychainItemRef itemRef;
	
	if(SecKeychainAddGenericPassword(NULL, [serviceName length], [serviceName UTF8String], [newUsername length], [newUsername UTF8String], [newPassword length], [newPassword UTF8String], NULL))
	{
		SecKeychainFindGenericPassword(NULL, [serviceName length], [serviceName UTF8String], 0, NULL, NULL, NULL, &itemRef);
		SecKeychainItemDelete(itemRef);
		SecKeychainAddGenericPassword(NULL, [serviceName length], [serviceName UTF8String], [newUsername length], [newUsername UTF8String], [newPassword length], [newPassword UTF8String], NULL);
	}
	//CFRelease(&itemRef);
}

@end
